﻿using System;
using System.Collections.Generic;
using System.Xml;
using System.Xml.Linq;

namespace WindowsGame.Library.ProxyObjects
{
	public interface IProxyObjectManager
	{
		void Parse(XElement root, String file);
		void Clear();

		IDictionary<String, String> ProxyNames { get; }
		IDictionary<String, ProxyObject> ProxyObjects { get; }
	}

	public class ProxyObjectManager : IProxyObjectManager
	{
		public ProxyObjectManager()
		{
			ProxyNames = new Dictionary<String, String>();
			ProxyObjects = new Dictionary<String, ProxyObject>();
		}

		public void Parse(XElement root, String file)
		{
			XName xName = XName.Get("Asset");
			IEnumerable<XElement> nodes = root.Elements(xName);

			foreach (XElement node in nodes)
			{
				ProxyObject proxyObject = ParseProxyObject(node);
				ProxyObjects.Add(proxyObject.Name, proxyObject);
				ProxyNames.Add(proxyObject.Name, file);
			}
		}

		public void Clear()
		{
			ProxyNames.Clear();
			ProxyObjects.Clear();
		}

		public ProxyObject ParseProxyObject(XElement node)
		{
			// Object name.
			XAttribute attribute = node.Attribute(XName.Get("name"));
			String name = attribute.Value;

			ProxyObject proxyObject = null;
			attribute = node.Attribute(XName.Get("type"));
			if (null == attribute)
			{
				proxyObject = new ProxyObject(name);
			}
			else
			{
				String type = attribute.Value;
				proxyObject = new ProxyObject(name, type);
			}

			// Object components.
			IEnumerable<XElement> elements = node.Elements();
			foreach (XElement element in elements)
			{
				XmlNodeType xmlNodeType = element.NodeType;
				if (xmlNodeType != XmlNodeType.Element)
				{
					continue;
				}

				ProxyComponent component = ParseProxyComponent(element);
				proxyObject.AddComponent(component);
			}

			return proxyObject;
		}

		public ProxyComponent ParseProxyComponent(XElement element)
		{
			// Component name.
			XAttribute idAttribute = element.Attribute(XName.Get("id"));
			String elemData = idAttribute != null ? idAttribute.Value : "0";

			String elemName = element.Name.ToString();
			String compName = String.Format("{0}_{1}", elemName, elemData);

			ProxyComponent component = new ProxyComponent(compName);

			// Component properties.
			IEnumerable<XAttribute> attributes = element.Attributes();
			foreach (XAttribute attribute in attributes)
			{
				String key = attribute.Name.ToString().ToLower();
				Object value = attribute.Value;

				component.AddProperty(key, value);
			}

			return component;
		}

		public IDictionary<String, String> ProxyNames { get; private set; }
		public IDictionary<String, ProxyObject> ProxyObjects { get; private set; }
	}
}